﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using Jerry.DroidBuilder.Controls;

namespace Jerry.DroidBuilder.Common
{
    public class BackgroundRunner
    {
        private static IDictionary<BackgroundWorker, WaitLock> _lockDict;

        static BackgroundRunner()
        {
            _lockDict = new Dictionary<BackgroundWorker, WaitLock>();
        }

        public static void Run(Action action)
        {
            var waitLock = WaitLock.Acquire();
            var backgroundWorker = new BackgroundWorker();

            _lockDict.Add(backgroundWorker, waitLock);

            backgroundWorker.RunWorkerCompleted += OnBackgroundWorkerRunWorkerCompleted;
            backgroundWorker.DoWork += delegate { action(); };

            backgroundWorker.RunWorkerAsync();
        }

        private static void OnBackgroundWorkerRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            var backgroundWorker = sender as BackgroundWorker;
            var waitLock = _lockDict[backgroundWorker];

            _lockDict.Remove(backgroundWorker);

            waitLock.Dispose();
        }
    }
}
